package com.info.provider.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.info.provider.redis.RedisUtil;
import com.mars.app.exception.ErrorCodeMsg;
import com.mars.app.exception.SystemException;
import com.mars.app.exception.WeChatInteractException;
import com.mars.app.utils.MarsAssert;
import com.mars.app.wetchat.WeChatStoreMsg;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by pengshuo on 2018/2/2 11:43
 * Description:
 * Modified By:
 * Version:
 *
 * @author pengshuo
 */
@Service
public class SessionService {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取缓存的appId
     *
     * @param thirdSessionId 本地key
     * @return appId
     */
    public String appId(String thirdSessionId) throws SystemException {
        try {
            MarsAssert.check(thirdSessionId != null,new WeChatInteractException(ErrorCodeMsg.LOCAL_CACHE_EXPIRE));
            // 获取缓存中的微信sessionKey
            Object storeInfo = redisUtil.get(thirdSessionId);
            // check storeInfo
            MarsAssert.check(storeInfo != null,new WeChatInteractException(ErrorCodeMsg.LOCAL_CACHE_EXPIRE));

            // sessionKey
            WeChatStoreMsg sessionKey = objectMapper.readValue((String) storeInfo,WeChatStoreMsg.class);

            String openId = sessionKey.getOpenId();

            MarsAssert.check(StringUtils.isNotBlank(openId),new SystemException(ErrorCodeMsg.GET_CACHE_APPID_FAIL));

            return openId;
        }catch (Exception e){
            logger.error("获取缓存的 appId  Exception: {}",e);
            throw new SystemException(ErrorCodeMsg.GET_CACHE_APPID_FAIL,e);
        }
    }

    /**
     * check local session is exist or not ; is not exist throw exception
     * @param thirdSessionId
     * @return
     */
    public void checkThirdSession(String thirdSessionId){
        try {
            if(StringUtils.isBlank(appId(thirdSessionId))){
                throw new SystemException(ErrorCodeMsg.LOCAL_CACHE_EXPIRE);
            }
        }catch (Exception e){
            logger.error("session expire  Exception: {}",e);
            throw new SystemException(ErrorCodeMsg.LOCAL_CACHE_EXPIRE,e);
        }
    }
}
